package ctrhost

import (
	"github.com/astaxie/beego/logs"
	"fmt"
	"sort"
	"cloud_worm/util/umodels/mysqldb"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
	"cloud_worm/util/uhttp"
	"cloud_worm/wormweb/controllers/ctrconfig"
)

// machine相关的
type MachineController struct {
	ctrconfig.LoginCtr
}

// /host/machine/all?page_count=&page=&status=&apply_id=&ip=&worm_id=(get)
func (a *MachineController) ListMachine() {
	a.Manager()

	offset, limit := a.DealPage()
	status, err := a.GetInt("status", mysqldb.StatusAll)
	applyId, err := a.GetInt("apply_id", mysqldb.SelectIntAll)
	ip := a.GetString("ip", mysqldb.SelectStrAll)
	wormId := a.GetString("worm_id", mysqldb.SelectStrAll)

	// 根据，获取上线的机器总数
	m := &dbmanager.Machine{}
	count, err := m.Count(status, int64(applyId), ip, wormId)
	if err != nil {
		logs.Error(fmt.Sprintf("error in get count: %s", err.Error()))
		data := map[string]interface{}{"total": 0, "data": []dbmanager.Machine{}}
		a.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "get count error.", data)
		a.ServeJSON()
		return
	}
	if count == 0 {
		data := map[string]interface{}{"total": 0, "data": []dbmanager.Machine{}}
		a.Data["json"] = uhttp.CreateOkResponse(data)
		a.ServeJSON()
		return
	}

	// 获取机器情况: todo: xxxxxxxx GetMachinesBrief
	machines, err := m.GetMachinesBrief(offset, limit, status, int64(applyId), ip, wormId)
	if err != nil {
		logs.Error(fmt.Sprintf("select machine failed: %s", err.Error()))
		data := map[string]interface{}{"total": 0, "data": []dbmanager.Machine{}}
		a.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "select machine failed.", data)
		a.ServeJSON()
		return
	}

	mList := dbmanager.MachineBriefList(machines)
	sort.Sort(mList)
	data := map[string]interface{}{"total": count, "data": mList}
	a.Data["json"] = uhttp.CreateOkResponse(data)
	a.ServeJSON()
	return
}
